package com.purong.purong.activity;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.adapter.CarBrandAdapter;
import com.purong.purong.bean.CarBrandBean;
import com.purong.purong.bean.CarBrandDataBean;
import com.purong.purong.util.CharacterParser;
import com.purong.purong.util.PinyinComparator;
import com.purong.purong.widget.LoadingView;
import com.purong.purong.widget.SideBar;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by user on 2017/9/15.
 */
public class CarBrandActivity extends BaseActivity {
    private EditText mEditText;
    public TextView dialog;
    private SideBar mSidBar;
    private RecyclerView mRecyclerView;

    private List<CarBrandBean> sourceDataList=new ArrayList<>();
    private List<CarBrandBean> dataList=new ArrayList<>();
    private CarBrandAdapter mAdapter;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private LoadingView loadingView;


    @Override
    public int getRootViewId() {
        return R.layout.activity_car_brand;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void initView(){
        showTitle("选择车辆品牌");
        showLeft(R.drawable.home_icon_close, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CarBrandActivity.this.finish();
            }
        });
        loadingView=(LoadingView)findViewById(R.id.loading_view);
        loadingView.setNoResultToast("暂无相关品牌","");
        loadingView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getCarBrand();
            }

            @Override
            public void onRefresh() {

            }
        });

        mRecyclerView=(RecyclerView)findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter=new CarBrandAdapter(this);

        mAdapter.setData(sourceDataList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnBrandClickListener(new CarBrandAdapter.OnBrandClickListener() {
            @Override
            public void onClick(CarBrandBean area) {
                Intent intent=new Intent();
                intent.putExtra("CAR_BRAND",area);
                setResult(RESULT_OK,intent);
                CarBrandActivity.this.finish();
            }
        });
        characterParser = CharacterParser.getInstance();
        pinyinComparator = PinyinComparator.getInstance();
        mSidBar = (SideBar)findViewById(R.id.sidrbar);
        dialog = (TextView)findViewById(R.id.group_dialog);
        mSidBar.setTextView(dialog);
        mSidBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                if (dataList.size() == 0) {
                    return;
                }
                int position = mAdapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    ((LinearLayoutManager)mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(position+1,0);
                }

            }
        });
        mEditText=(EditText)findViewById(R.id.edit_text);
        mEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    public void initData() {
        getCarBrand();
    }

    private void getCarBrand(){
        loadingView.loading();
        Map<String, String> params = new LinkedHashMap<String, String>();
        if (!request(Contant.CAR_BRAND, params, true, false)){
            loadingView.fail();
        }

    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy()){
            return;
        }
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.CAR_BRAND)){
            if (responseInfo.isRequestOk){
                try{
                    CarBrandDataBean bean= JSON.parseObject(responseInfo.content,CarBrandDataBean.class);
                    if (bean.getCar_brand_list().getAllBrand()!=null){
                        dataList.clear();
                        dataList.addAll(bean.getCar_brand_list().getAllBrand());
                        if (dataList.size()>0){
                            loadingView.finish();
                            setData();
                        }else {
                            loadingView.noResult();
                        }
                    }
                }catch (Exception e){
                    loadingView.fail();
                }

            }else {
                loadingView.fail();
            }
        }
    }

    public void setData() {
        sourceDataList.clear();
        if (dataList != null && dataList.size() > 0) {

            sourceDataList.addAll(filledData(dataList));
//                    sourceDataList = ; //过滤数据为有字母的字段  现在有字母 别的数据没有
        }

        //还原除了带字母字段的其他数据
        for (int i = 0; i < dataList.size(); i++) {
            sourceDataList.get(i).setCar_brand_name(dataList.get(i).getCar_brand_name());
            sourceDataList.get(i).setCar_brand_id(dataList.get(i).getCar_brand_id());
            sourceDataList.get(i).setCar_brand_url(dataList.get(i).getCar_brand_url());
            sourceDataList.get(i).setCar_brand_name_py(dataList.get(i).getCar_brand_name_py());
        }

        // 根据a-z进行排序源数据
        Collections.sort(sourceDataList, pinyinComparator);
        mAdapter.notifyDataSetChanged();
//                adapter = new FriendAdapter(getActivity(), sourceDataList);
//                mListView.setAdapter(adapter);
    }

    private List<CarBrandBean> filledData(List<CarBrandBean> list) {
        ArrayList<CarBrandBean> mFriendList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            CarBrandBean friendModel = new CarBrandBean();

            friendModel.setCar_brand_name(list.get(i).getCar_brand_name());
            //汉字转换成拼音
            String pinyin;
            pinyin = characterParser.getSelling(list.get(i).getCar_brand_name());

            String sortString;
            if (pinyin.equals("")) {
                sortString = "";
            } else {
                sortString = pinyin.substring(0, 1).toUpperCase();
            }


            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                friendModel.setLetters(sortString.toUpperCase());
            } else {
                friendModel.setLetters("#");
            }

            mFriendList.add(friendModel);
        }
        return mFriendList;

    }

    private void filterData(String filterStr) {
        List<CarBrandBean> filterDateList = new ArrayList<>();

        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = sourceDataList;
        } else {
            filterDateList.clear();
            for (CarBrandBean friendModel : sourceDataList) {
                String name;
                name = friendModel.getCar_brand_name();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(friendModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        mAdapter.updateListView(filterDateList);
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.location_city:
                showToast("当前定位城市");
                break;
        }
    }
}
